<template>
  <!-- 
            el-upload 上传图片
                action	必选参数，上传的地址	string
                list-type	文件列表的类型	string	text/picture/picture-card	text
                on-preview	点击文件列表中已上传的文件时的钩子	function(file)	—	—
                on-remove	文件列表移除文件时的钩子	function(file, fileList)	—	—
                on-success	文件上传成功时的钩子	function(response, file, fileList)
                multiple	是否支持多选文件	boolean
                file-list	上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]	array	—	[]
                disabled	是否禁用	boolean	—	false
                limit	最大允许上传个数	number	—	—
                on-exceed	文件超出个数限制时的钩子	function(files, fileList)

                方法：
                    clearFiles    
         -->
  <el-upload v-model:file-list="fileList" :action="uploadUrl" list-type="picture-card"
    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :multiple="true" :on-success="handleSuccess"
    ref="deletepic">
    <el-icon>
      <Plus />
    </el-icon>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script setup>
import { ref, watch, defineEmits, defineProps } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { uploadUrl, host } from '@/api/base.js'

// 定义组件的自定义事件
const emits = defineEmits(['getimg'])
// 定义组件的props
const props = defineProps(['imgs'])

// 定义响应式数据
const fileList = ref([])
const imageList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

// 处理图片 URL
const processImageUrl = function (url) {
  if (url.includes('http://localhost:80')) {
    return url
  }
  const newUrl = url.slice(7)
  return `${host}/${newUrl}`
}

// 处理文件移除事件
const handleRemove = function (uploadFile, uploadFiles) {
  const index = imageList.value.findIndex(function (url) {
    return url === uploadFile.url
  })
  if (index !== -1) {
    imageList.value.splice(index, 1)
  }
  const imgUrls = imageList.value
  emits('getimg', imgUrls)
}

// 处理文件上传成功事件
const handleSuccess = function (response, uploadFile, uploadFiles) {
  if (response && response.url) {
    uploadFile.url = processImageUrl(response.url)
    const processedUrl = processImageUrl(response.url)
    imageList.value.push(processedUrl)
  }
  const imgUrls = imageList.value
  emits('getimg', imgUrls)
}

// 处理图片预览事件
const handlePictureCardPreview = function (uploadFile) {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

const deletepic = ref(null)
const clear = () => {
  deletepic.value.clearFiles()
}
// 暴露子组件的方法
defineExpose({
  clear
});

// 监听props.imgs的变化
watch(() => props.imgs, function (newval) {
  try {
    const arr = JSON.parse(props.imgs)
    // console.log(arr);
    fileList.value.length=0
    if (arr.length !== 0) {
      arr.forEach(function (ele) {
        fileList.value.push({ name: '', url: ele })
        imageList.value.push(ele)
      })
    }
  } catch (error) {
    
  }
})
</script>